/**
 * 
 */
package com.rfid.transport;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.rfid.reader.RfidReader;

/**
 * @author hrb
 *
 */
public final class TransportThreadManager {
	private static TransportThreadManager manager = null;
	private static Thread readThread = null;
	private Selector selector = null;
	private HashMap<String,RfidReader> readerMap;	//support non-net interface
	private TransportThreadManager() throws IOException {
		selector = Selector.open();
		readerMap = new HashMap<String,RfidReader>();
	}
	
	public int AddTransport(Transport transport){
		
		return 0;
	}
	
	public static TransportThreadManager getInstance() throws IOException {
		if ( null == manager) {
			initilizeTransportManager();
		}
		return manager;
	}
	
	public static void initilizeTransportManager() throws IOException {
		// create one thread for receive data.
		if ( null == manager) {
			synchronized (TransportThreadManager.class){
	            if(manager == null){
	            	manager = new TransportThreadManager();
	            }           
	        }
		}
		initilizeThreads();
	}
	
	public Iterator<Entry<String,RfidReader>> getReaderIterator(){
		return readerMap.entrySet().iterator();
	}
	public Selector getSelector() {
		return this.selector;
	}
	
	public static void initilizeThreads() {
		if (null == readThread) {
			readThread = new ReceiveThread();
			readThread.start();
		}	
	}
	
	public void Start() {
		
	}

	public int AddRfidReader(RfidReader reader) throws IOException
	{
		int result = 0;
		if (RfidReader.CONNECT_TYPE_NET_TCP_CLIENT == reader.connectType)
		{
			TransportTcpClient transport = (TransportTcpClient) reader.getTransport();
			transport.clientChannel.configureBlocking(false);
			transport.clientChannel.register(selector, SelectionKey.OP_READ,reader);
		}
		else if ( RfidReader.CONNECT_TYPE_NET_TCP_SERVER == reader.connectType)
		{
			
		}
		else if ( RfidReader.CONNECT_TYPE_NET_UDP == reader.connectType)
		{
			TransportUdp transport = (TransportUdp) reader.getTransport();
			transport.socketChannel.configureBlocking(false);
			transport.socketChannel.register(selector, SelectionKey.OP_READ,reader);
		}
		else if (RfidReader.CONNECT_TYPE_SERIALPORT == reader.connectType)
		{
			
		}
		readerMap.put(reader.getKey(), reader);
		return result;
	}
	
}
